import cv2
import numpy as np

# 初始化画布尺寸
canvas_width = 600
canvas_height = 600

# 初始化画布为白色
canvas = np.ones((canvas_height, canvas_width, 3), dtype=np.uint8) * 255

# 初始化状态
drawing = False  # 是否正在绘制
mode = 'line'  # 默认模式为画线
ix, iy = -1, -1  # 起始点坐标

# 鼠标回调函数
def draw_circle(event, x, y, flags, param):
    global ix, iy, drawing, mode

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing == True:
            if mode == 'line':
                cv2.line(canvas, (ix, iy), (x, y), (0, 0, 0), 2)
                ix, iy = x, y
            elif mode == 'rectangle':
                cv2.rectangle(canvas, (ix, iy), (x, y), (0, 0, 0), 2)
            elif mode == 'circle':
                cv2.circle(canvas, (x, y), 5, (0, 0, 0), -1)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if mode == 'circle':
            cv2.circle(canvas, (x, y), abs(x-ix), (0, 0, 0), -1)

cv2.namedWindow('Drawing')
cv2.setMouseCallback('Drawing', draw_circle)

while True:
    cv2.imshow('Drawing', canvas)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('l'):
        mode = 'line'
    elif k == ord('r'):
        mode = 'rectangle'
    elif k == ord('c'):
        mode = 'circle'
    elif k == 27:  # 按下 ESC 键退出
        break

cv2.destroyAllWindows()